/*jslint maxerr: 50, indent: 4, browser: true */
/*global define */

(function (undef) {
    "use strict";

    define("extend", ["mergeModules", "init", "array.length", "array.isArray", "object.isPlainObject"], function (make) {
        var buri = make.mergeModules(arguments),
            config = {
                "compatability": {}
            };

        function extend() {
            var args = arguments,
                target = args[0] || {},
                length = buri.array.length(args),
                deep = false,
                i = 1,
                src,
                copy,
                name,
                options,
                clone;

            if (typeof target === "boolean") {
                deep = target;
                target = args[1] || {};
                i = 2;
            }

            if (typeof target !== "object" && typeof target !== "function") {
                target = {};
            }

            while (i < length) {
                options = args[i];
                if (options !== undef && options !== null) {
                    for (name in options) {
                        if (target !== copy) {
                            src = target[name];
                            copy = options[name];
                            if (deep && copy && (buri.array.isArray(copy) || buri.object.isPlainObject(copy))) {
                                if (buri.array.isArray(copy)) {
                                    if (src && buri.array.isArray(src)) {
                                        clone = src;
                                    } else {
                                        clone = [];
                                    }
                                } else {
                                    if (buri.object.isPlainObject(src)) {
                                        clone = src;
                                    } else {
                                        clone = {};
                                    }
                                }

                                target[name] = extend(deep, clone, copy);
                            } else if (copy !== undef) {
                                target[name] = copy;
                            }
                        }
                    }
                }

                i += 1;
            }

            return target;
        }

        extend.init = function (options) {
            buri.init(config, options);
            buri.array.length.init(config);
            buri.array.isArray.init(config);
            buri.object.isPlainObject.init(config);
        };

        return {
            "extend": extend
        };
    });
}());
